package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private StringRedisTemplate redistemplate;
    @Autowired
    private SystemUserService systemUserService;
    /**
     * @author gengjian
     * @date 2024/12/13 20:02:14
     * 获取图形验证码
     */
    @Override
    public CaptchaVo getCaptcha() {
        //生成图形验证码 指定长宽验证码几位
        SpecCaptcha specCaptcha = new SpecCaptcha(130,48,4);
        //图片想要传到json字符串中要用tobase64
        String specCaptchaBase64 = specCaptcha.toBase64();
        //获取正确验证码
        String text = specCaptcha.text();
        //获取uuid
        UUID uuid = UUID.randomUUID();
        //拼接redis的key
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + uuid;
        //存储到redis中，还要加ttl 过期时间60s
        redistemplate.opsForValue().set(key,text,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        return new CaptchaVo(specCaptchaBase64,key);
    }

    /**
     * @author gengjian
     * @date 2024/12/13 23:34:10
     * 登录功能
     */
    @Override
    public String login(LoginVo loginVo) {
        //先校验验证码
        String captchaKey = loginVo.getCaptchaKey();
        String captcha = redistemplate.opsForValue().get(captchaKey);
        if (ObjectUtils.isEmpty(captcha)){
            //不能根据key查到value则说明过期
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        if (!captcha.equalsIgnoreCase(loginVo.getCaptchaCode())){
            //不相等则输入验证码错误
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //校验用户名是否存在
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getUsername,loginVo.getUsername());
        SystemUser systemUser = systemUserService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(systemUser)){
            //为空则用户名错误 不存在
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //判断用户是否被禁用
        BaseStatus status = systemUser.getStatus();
        if (status.getCode() == BaseStatus.DISABLE.getCode()){
            //用户被禁用
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //校验密码是否正确 传过来的密码要加密
        if (!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))){
            //true则密码错误
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //登录成功 生成token
        String token = JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
        //返回token
        return token;
    }

    /**
     * @author gengjian
     * @date 2024/12/14 08:32:48
     * 获取登录用户用户姓名和头像
     */
    @Override
    public SystemUserInfoVo getLoginUserInfo(LoginUser loginUser) {
        //token解析 获取userid 去查 这一步不要了因为本地线程中有
//        Integer userId = (Integer) JwtUtil.parseToken(token).get("userId");
        //查数据库并封装vo
        SystemUser systemUser = systemUserService.getById(loginUser.getUserId());
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }
}
